package com.gaogzhen.designPattern.producerConsumer.fullTextSearch;

import com.gaogzhen.threadPool.BlockingQueue;

import java.util.concurrent.Semaphore;

/**
 * @author Administrator
 * @version 1.0
 * @date 2022-10-28 10:01
 *
 * 基于Semaphore的支持流量控制的通道实现
 */
public class SemaphoreBasedChannel<D> implements Channel<D> {

    private final BlockingQueue<D> queue;
    private final Semaphore semaphore;

    public SemaphoreBasedChannel(BlockingQueue<D> queue, Semaphore semaphore) {
        this.queue = queue;
        this.semaphore = semaphore;
    }

    @Override
    public void put(D data) throws InterruptedException {
        semaphore.acquire();
        try {
            queue.put(data);
        } finally {
            semaphore.release();
        }
    }

    @Override
    public D take() throws InterruptedException {
        return queue.take();
    }
}
